<template>
  <div class="rich-text">
    <div ref="editor" style="text-align:left"></div>
  </div>
</template>

<script>
import E from 'wangeditor';
import { getOssToken } from '@/api/upload';
import { generateFileName } from '@/utils';
import OSS from 'ali-oss';

export default {
  props: {
    value: String,
  },
  data() {
    return {
      editor: null,
      isInit: false,
    };
  },
  watch: {
    value(val) {
      this.editor.txt.html(val);
    },
  },
  mounted() {
    this.editor = new E(this.$refs.editor);
    this.editor.customConfig.onchange = (html) => {
      this.$emit('input', html);
    };
    this.editor.customConfig.customUploadImg = async (files, insert) => {
      const file = files[0];
      const { name } = file;
      const result = await getOssToken();
      const {
        accessKeyId, accessKeySecret, securityToken, region, bucketName, endpoint,
      } = result;
      const fileName = generateFileName(name);
      this.ossClient = new OSS({
        accessKeyId,
        accessKeySecret,
        stsToken: securityToken,
        bucket: bucketName,
        endpoint,
        region,
      });
      const { url } = await this.ossClient.put(fileName, file);
      insert(url);
    };
    this.editor.create();
    this.editor.txt.html(this.value);
  },
};
</script>
<style lang="scss" scoped>

</style>
